package com.thisblog.auth.boot.service;

import com.thisblog.auth.boot.domain.User;
import com.thisblog.common.core.result.Result;
import com.thisblog.common.core.result.ResultCode;
import com.thisblog.common.web.utils.RequestUtils;
import com.thisblog.homepage.api.UserFeignClient;
import com.thisblog.homepage.pojo.dto.UserDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 自定义用户认证和授权
 */
@Service
@AllArgsConstructor
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

   private UserFeignClient userFeignClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String clientId = RequestUtils.getAuthClientId();
        User user = null;
        Result result = userFeignClient.getUserByUsername(username);
        log.info("获取用户信息：{}", result.toString());
        if (ResultCode.SUCCESS.getCode().equals(result.getCode())) {
            UserDTO userDTO = (UserDTO) result.getData();
            user = new User(userDTO);
        }
        if (user == null || user.getId() == null) {
            throw new UsernameNotFoundException(ResultCode.USER_NOT_EXIST.getMsg());
        } else if (!user.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        } else if (!user.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定!");
        } else if (!user.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期!");
        }
        /*User user = new User();
        user.setId((long) 2);
        user.setUsername("admin");
        user.setPassword("{bcrypt}$2a$10$dLq3.pXNwTNqWabsRfJX4ej8Htk/vUWuHh.LvITq5BrU8u.dYvZpC");
        user.setEnabled(true);
        List role = new ArrayList<>();
        SimpleGrantedAuthority simpleGrantedAuthority  = new SimpleGrantedAuthority("2");
        role.add(simpleGrantedAuthority);
        user.setAuthorities(role);*/
        return user;
    }
}
